<?php if( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<?php

class Transaction extends CI_Controller {

    var $_public_view;

    function __construct() {
        parent::__construct();
        $this->load->model('model_perjalanan', 'mtrip');
        $this->load->helper('url');
        //$this->load->helper('get_profile');
        $this->load->library('session');
        $this->config->load('ojexcom');
        $this->_public_view = $this->config->item('public_view');
    }

    function index(){
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //header('Content-Type: application/json');
        $data_output['success'] = "false";
        $error = 0;
        $userid = $id;
        $providerId = $this->input->post('providerId');
        $idTrip = $this->input->post('idTrip');
        $paymentMethod = $this->input->post('paymentMethod');
        $transId = 0;
        $price = $this->input->post('price');
        $departTime = date('Y-m-d H:i',strtotime($this->input->post('departTime')));
        $source_label = $this->input->post('source_label');
        $source_latitude = $this->input->post('source_latitude');
        $source_longitude = $this->input->post('source_longitude');
        $destination_label = $this->input->post('destination_label');
        $destination_latitude = $this->input->post('destination_latitude');
        $destination_longitude = $this->input->post('destination_longitude');
        if($paymentMethod == "P"){
            if($this->isPremium($userid) != 1){
                $error = 77; // user bukan premium
            }               
        }
        if($error == 0 && $paymentMethod == "P"){
            if($this->isPremium($providerId) != 1 ){
                $error = 88; // provider bukan premium
            }               
        }

        // Insert data ke table transaction
        if($error == 0){
            $input_data = array(
                'userId' => $userid,
                'providerId' => $providerId,
                'idTrip' => $idTrip,
                'departTime' => $departTime,
                'source_label' => $source_label,
                'source_latitude' => $source_latitude,
                'source_longitude' => $source_longitude,
                'destination_label' => $destination_label,
                'destination_latitude' => $destination_latitude, 
                'destination_longitude' => $destination_longitude,
                'paymentMethod' => $paymentMethod,
                'price' => $price,
                'privacy' => $this->input->post('privacy'),
            );
            $this->db->insert('transaction', $input_data);
            if($this->db->affected_rows() < 1){
                $error = 99; // data tidak masuk ke database
            }
        }

        // insert data ke table transactionStatus
        if($error == 0){
            
            $query = $this->db->query("SELECT `id`FROM `transaction` WHERE userId = ".$userid." AND providerId = ".$providerId." ORDER BY `id` DESC");
            $row = $query->row();
            $transId = $row->id;
            $status = "S";
            $now = date("Y-m-d H:i:s");
            if($paymentMethod == "P"){
                $status = "L";
            }       
            if($error == 0 && $status == "S"){
                $input_data = array(
                    'idTransaction' => $transId,
                    'timeStamp' => $now,
                    'status' => $status,
                );
                $this->db->insert('transactionStatus', $input_data);
                if($this->db->affected_rows() < 1){
                    $error = 99; // data tidak masuk ke database
                }
            }else if($error == 0 && $status == "L"){
                $idx = $this->overBook($price,$this->getRekening($userid),$this->getRekening($providerId));
                if($idx!=NULL && $idx > 0){
                    $input_data = array(
                        'idx' => $idx,
                    );
                    
                    $this->db->where('id', $transId);
                    $this->db->update('transaction', $input_data);
                    if($this->db->affected_rows() < 1){
                        $error = 99; // data tidak masuk ke database
                    }else{
                        
                        $input_data = array(
                            'idTransaction' => $transId,
                            'timeStamp' => $now,
                            'status' => $status,
                        );
                        $this->db->insert('transactionStatus', $input_data);
                        if($this->db->affected_rows() < 1){
                            $error = 99; // data tidak masuk ke database
                        }
                    }
                }else{
                    $error = 66; // tidak dapat melakukan transaksi point
                    $this->db->where('id', $transId);
                    $this->db->delete('transaction', $input_data);
                }
            }
        }

        if($error == 0){
            $data_output['success'] = "true";
            
            $query_status = $this->db->query("SELECT id FROM `transactionStatus` WHERE idTransaction=".$transId." AND status='".$status."' ORDER BY id DESC");
            $row_status = $query_status->row();
            $transStatusId = $row_status->id;
            
            // notifikasi pasif untuk user
            $input_data = array(
                'type' => "T",
                'userId' => $userid,
                'transactionStatusId' => $transStatusId,
            );
            $this->db->insert('notifications', $input_data);
            if($status == 'L'){
                // notifikasi aktif untuk user
                $input_data = array(
                    'type' => "T",
                    'need_response' => 1,
                    'userId' => $userid,
                    'transactionStatusId' => $transStatusId,
                );
                $this->db->insert('notifications', $input_data);
                // notifikasi pasif untuk provider
                $input_data = array(
                    'type' => "T",
                    'userId' => $providerId,
                    'transactionStatusId' => $transStatusId,
                );
                $this->db->insert('notifications', $input_data);
            }
            // notifikasi aktif untuk provider
            $input_data = array(
                'type' => "T",
                'need_response' => 1,
                'userId' => $providerId,
                'transactionStatusId' => $transStatusId,
            );
            $this->db->insert('notifications', $input_data);
            
            if($this->db->affected_rows() > 0){
                
                //$this->getNotification();
                
                if ($this->getIOSToken($userid) != NULL){
                    //$this->iospush->push($this->getIOSToken($userid),"Submit Transaksi Berhasil");
                }
                if ($this->getIOSToken($providerId) != NULL){
                    //$this->iospush->push($this->getIOSToken($providerId),$this->getNameById($userid)." ingin menumpang kepada anda");
                }
                
            }
            
            echo "Memproses permintaan, tunggu sebentar ...";
            redirect('profil/detail/'.$providerId,'refresh');
            // $data = array(
            //     'output'=> $this->get($providerId,$id),
            //     'page_title' => 'Profil',
            //     'page_content' => 'myprofile',
            //     'isLogin' => $isLogin, 'user' => $user, 'id' => $id, 'isUpdate' => false);
            // $this->load->view($this->_public_view, $data);
        }

        if($error > 0){
            $data_output['success'] = "false";
            $data_output['error'] = $error;
            echo json_encode($data_output);
        }
        // $data = array(
        //     'output'=> $data_output,
        //     'page_title' => 'Berhasil',
        //     'page_content' => 'transaction',
        //     'isLogin' => $isLogin, 'user' => $user, 'id' => $id
        //         );
        // $this->load->view($this->_public_view, $data);

    }

    function getNameById($userid){
        $query = $this->db->query("SELECT `name` FROM `user` WHERE `id`=".$userid);
        $row = $query->row();
        return $row->name;
    }

    function getAvatarById($userid){
        $query = $this->db->query("SELECT `avatar` FROM `user` WHERE `id`=".$userid);
        $row = $query->row();
        return $row->avatar;
    }

        
    function getLastUpdatedAvatar($userid){
        $query = $this->db->query("SELECT `lastUpdatedAvatar` FROM `user` WHERE `id`=".$userid."");
        $row = $query->row();
        return $row->lastUpdatedAvatar;
    }
    
    function isPremium($userid){
        $query = $this->db->query("SELECT `isPremium` FROM `user` WHERE `id`=".$userid);
        $row = $query->row();
        return $row->isPremium;
    }

    function getIOSToken($userid){
        $query = $this->db->query("SELECT `ios_token` FROM `user` WHERE `id`=".$userid);
        $row = $query->row();
        return $row->ios_token;
    }
    
    function getRekening($userid){
        $query = $this->db->query("SELECT `no_rekening` FROM `user` WHERE `id`=".$userid);
        $row = $query->row();
        return $row->no_rekening;
    }

    function getIDX($transId){
        $query = $this->db->query("SELECT `idx` FROM `transaction` WHERE `id`=".$transId);
        $row = $query->row();
        return $row->idx;
    }
    
    function overBook($jumlah,$asal,$tujuan){
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/overbook?jumlah='.$jumlah.'&asal='.$asal.'&tujuan='.$tujuan;
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['idx']))            return $response['idx'];
        else        return NULL;
    }
    
    function overBookCancel($idx){
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/cancelpoint/id/'.$idx;
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status'])){
            if($response['status'] == "success"){
                return TRUE;
            }else{
                return FALSE;
            }
        }else{
            return FALSE;
        }       
    }
    
    function overBookRealese($idx){
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/realesepoint/id/'.$idx;
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['status'])){
            if($response['status'] == "success"){
                return TRUE;
            }else{
                return FALSE;
            }
        }else{
            return FALSE;
        }       
    }

    function confirmProvider(){
        //header('Content-Type: application/json');

        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        $success = true;
        //$idTransaction = $this->input->post('idTransaction');
        $idTransaction = $str_id;
        //$myId = $this->input->post('userId');
        $myId = $id;
        $query = $this->db->query("SELECT n.transactionStatusId, t.providerId FROM notifications n JOIN transactionStatus s ON s.id=n.transactionStatusId JOIN `transaction` t ON t.id=s.idTransaction WHERE s.idTransaction=".$idTransaction);
        $row = $query->row();
        // notifikasi sebelumnya di anggap sudah di baca
        foreach($query->result() as $row){
            if($row->providerId != $myId){
                $success = false;
                break;
            }else{
                $this->db->where('transactionStatusId', $row->transactionStatusId);
                $this->db->delete('notifications');
            }
        }
        if($success){
            // menambahkan status menjadi cancel
            $now = date("Y-m-d H:i:s");
            $input_data = array(
                'idTransaction' => $idTransaction,
                'timeStamp' => $now,
                'status' => "F",
            );
            $this->db->insert('transactionStatus', $input_data);
        }
        
        if($success && $this->db->affected_rows() > 0 ){
            $query_status = $this->db->query("SELECT s.id, t.userId, t.providerId, t.idTrip  FROM `transactionStatus` s JOIN transaction t ON s.idTransaction=t.id WHERE idTransaction=".$idTransaction." AND status='F' ORDER BY id DESC");
            if($query_status->num_rows()>0){
                $row_status = $query_status->row();
                $transStatusId = $row_status->id;
                $userid = $row_status->userId;
                $providerId = $row_status->providerId;
                $idTrip =  $row_status->idTrip;
                // notifikasi pasif untuk user
                $input_data = array(
                    'type' => "T",
                    'userId' => $userid,
                    'transactionStatusId' => $transStatusId,
                );
                $this->db->insert('notifications', $input_data);
                // notifikasi pasif untuk provider
                $input_data = array(
                    'type' => "T",
                    'userId' => $providerId,
                    'transactionStatusId' => $transStatusId,
                );
                $this->db->insert('notifications', $input_data);
                if($this->db->affected_rows() > 0){
                    $input_data = array(
                        'is_available' => 0,
                    );      
                    $this->db->where('id', $idTrip);
                    $this->db->update('trip', $input_data);
                    //$this->getNotification();
                    $this->get_notification();
                }
            }else{
                $data_output['success'] = "false";
                //echo json_encode($data_output);
            }
        }else{
            $data_output['success'] = "false";
            //echo json_encode($data_output);
        }
    }

    function cancelTransactionUser(){
        //header('Content-Type: application/json');

        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        //$idTransaction = $this->input->post('idTransaction');
        $idTransaction = $str_id;
        $query = $this->db->query("SELECT n.transactionStatusId FROM notifications n JOIN transactionStatus s ON s.id=n.transactionStatusId JOIN `transaction` t ON t.id=s.idTransaction WHERE s.idTransaction=".$idTransaction);
        $row = $query->row();
        // notifikasi sebelumnya di anggap sudah di baca
        foreach($query->result() as $row){
            $this->db->where('transactionStatusId', $row->transactionStatusId);
            $this->db->delete('notifications');
        }
        // menambahkan status menjadi cancel
        $now = date("Y-m-d H:i:s");
        $input_data = array(
            'idTransaction' => $idTransaction,
            'timeStamp' => $now,
            'status' => "C",
        );
        $this->db->insert('transactionStatus', $input_data);
        if($this->db->affected_rows() > 0 ){
            $query_status = $this->db->query("SELECT s.id, t.userId, t.providerId, t.idx, t.idTrip  FROM `transactionStatus` s JOIN transaction t ON s.idTransaction=t.id WHERE idTransaction=".$idTransaction." AND status='C' ORDER BY id DESC");
            $row_status = $query_status->row();
            $transStatusId = $row_status->id;
            $userid = $row_status->userId;
            $providerId = $row_status->providerId;
            $idx = $row_status->idx;
            $idTrip =  $row_status->idTrip;
            if($transStatusId != NULL){
                if($idx != NULL){
                    if($this->overBookCancel($idx) == TRUE){
                        // notifikasi pasif untuk user
                        $input_data = array(
                            'type' => "T",
                            'userId' => $userid,
                            'transactionStatusId' => $transStatusId,
                        );
                        $this->db->insert('notifications', $input_data);
                        // notifikasi pasif untuk provider
                        $input_data = array(
                            'type' => "T",
                            'userId' => $providerId,
                            'transactionStatusId' => $transStatusId,
                        );
                        $this->db->insert('notifications', $input_data);
                        if($this->db->affected_rows() > 0){
                            $input_data = array(
                                'is_available' => 1,
                            );      
                            $this->db->where('id', $idTrip);
                            $this->db->update('trip', $input_data);
                            //$this->getNotification();
                        }
                    }else{
                        $data_output['success'] = "false";
                        //echo json_encode($data_output);
                    }
                }else{
                    // notifikasi pasif untuk user
                    $input_data = array(
                        'type' => "T",
                        'userId' => $userid,
                        'transactionStatusId' => $transStatusId,
                    );
                    $this->db->insert('notifications', $input_data);
                    // notifikasi pasif untuk provider
                    $input_data = array(
                        'type' => "T",
                        'userId' => $providerId,
                        'transactionStatusId' => $transStatusId,
                    );
                    $this->db->insert('notifications', $input_data);
                    if($this->db->affected_rows() > 0){
                        $input_data = array(
                            'is_available' => 1,
                        );      
                        $this->db->where('id', $idTrip);
                        $this->db->update('trip', $input_data);
                        //$this->getNotification();
                    }
                }
            }else{
                $data_output['success'] = "false";
                //echo json_encode($data_output);
            }
        }else{
            $data_output['success'] = "false";
            //echo json_encode($data_output);
        }
        $data = array(
                'output'=> $this->get($providerId,$this->session->userdata('user_id')),
                'page_title' => 'Profil',
                'page_content' => 'myprofile',
                'isLogin' => $isLogin, 'user' => $user, 'id' => $id, 'isUpdate' => false);
            $this->load->view($this->_public_view, $data);
    }

    function cancelTransactionProvider(){
        //header('Content-Type: application/json');

        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        //$idTransaction = $this->input->post('idTransaction');
        $idTransaction = $str_id;
        $query = $this->db->query("SELECT n.transactionStatusId FROM notifications n JOIN transactionStatus s ON s.id=n.transactionStatusId JOIN `transaction` t ON t.id=s.idTransaction WHERE s.idTransaction=".$idTransaction);
        $row = $query->row();
        // notifikasi sebelumnya di anggap sudah di baca
        foreach($query->result() as $row){
            $this->db->where('transactionStatusId', $row->transactionStatusId);
            $this->db->delete('notifications');
        }
        // menambahkan status menjadi cancel
        $now = date("Y-m-d H:i:s");
        $input_data = array(
            'idTransaction' => $idTransaction,
            'timeStamp' => $now,
            'status' => "C",
        );
        $this->db->insert('transactionStatus', $input_data);
        if($this->db->affected_rows() > 0 ){
            $query_status = $this->db->query("SELECT s.id, t.userId, t.providerId, t.idx, t.idTrip  FROM `transactionStatus` s JOIN transaction t ON s.idTransaction=t.id WHERE idTransaction=".$idTransaction." AND status='C' ORDER BY id DESC");
            $row_status = $query_status->row();
            $transStatusId = $row_status->id;
            $userid = $row_status->userId;
            $providerId = $row_status->providerId;
            $idx = $row_status->idx;
            $idTrip =  $row_status->idTrip;
            if($transStatusId != NULL){
                if($idx != NULL){
                    if($this->overBookCancel($idx) == TRUE){
                        // notifikasi pasif untuk user
                        $input_data = array(
                            'type' => "T",
                            'userId' => $userid,
                            'transactionStatusId' => $transStatusId,
                        );
                        $this->db->insert('notifications', $input_data);
                        // notifikasi pasif untuk provider
                        $input_data = array(
                            'type' => "T",
                            'userId' => $providerId,
                            'transactionStatusId' => $transStatusId,
                        );
                        $this->db->insert('notifications', $input_data);
                        if($this->db->affected_rows() > 0){
                            $input_data = array(
                                'is_available' => 1,
                            );      
                            $this->db->where('id', $idTrip);
                            $this->db->update('trip', $input_data);
                            //$this->getNotification();
                        }
                    }else{
                        $data_output['success'] = "false";
                        //echo json_encode($data_output);
                    }
                }else{
                    // notifikasi pasif untuk user
                    $input_data = array(
                        'type' => "T",
                        'userId' => $userid,
                        'transactionStatusId' => $transStatusId,
                    );
                    $this->db->insert('notifications', $input_data);
                    // notifikasi pasif untuk provider
                    $input_data = array(
                        'type' => "T",
                        'userId' => $providerId,
                        'transactionStatusId' => $transStatusId,
                    );
                    $this->db->insert('notifications', $input_data);
                    if($this->db->affected_rows() > 0){
                        $input_data = array(
                            'is_available' => 1,
                        );      
                        $this->db->where('id', $idTrip);
                        $this->db->update('trip', $input_data);
                        //$this->getNotification();
                    }
                }
            }else{
                $data_output['success'] = "false";
                //echo json_encode($data_output);
            }
        }else{
            $data_output['success'] = "false";
            //echo json_encode($data_output);
        }
        // $data = array(
        //         'output'=> $this->get($providerId,$this->session->userdata('user_id')),
        //         'page_title' => 'Profil',
        //         'page_content' => 'myprofile',
        //         'isLogin' => $isLogin, 'user' => $user, 'id' => $id, 'isUpdate' => false);
        //     $this->load->view($this->_public_view, $data);
        $this->get_notification();
    }

    function dropOff(){
        //header('Content-Type: application/json');

        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        $success = true;
        //$idTransaction = $this->input->post('idTransaction');
        $idTransaction = $str_id;
        //$myId = $this->input->post('userId');
        $myId = $id;
        $query = $this->db->query("SELECT n.transactionStatusId, t.providerId  FROM notifications n JOIN transactionStatus s ON s.id=n.transactionStatusId JOIN `transaction` t ON t.id=s.idTransaction WHERE s.idTransaction=".$idTransaction);
        $row = $query->row();
        // notifikasi sebelumnya di anggap sudah di baca
        foreach($query->result() as $row){
            if($row->providerId != $myId){
                $success = false;
                break;
            }else{
                $this->db->where('transactionStatusId', $row->transactionStatusId);
                $this->db->delete('notifications');
            }
        }
        // menambahkan status menjadi cancel
        $now = date("Y-m-d H:i:s");
        $input_data = array(
            'idTransaction' => $idTransaction,
            'timeStamp' => $now,
            'status' => "D",
        );
        $this->db->insert('transactionStatus', $input_data);
        if($this->db->affected_rows() > 0 ){
            $query_status = $this->db->query("SELECT s.id, t.userId, t.providerId FROM `transactionStatus` s JOIN transaction t ON s.idTransaction=t.id WHERE idTransaction=".$idTransaction." AND status='D' ORDER BY id DESC LIMIT 1");
            $row_status = $query_status->row();
            $transStatusId = $row_status->id;
            $userid = $row_status->userId;
            $providerId = $row_status->providerId;
            if($transStatusId != NULL){
                // notifikasi pasif untuk user
                $input_data = array(
                    'type' => "T",
                    'userId' => $userid,
                    'need_response' => 1,
                    'transactionStatusId' => $transStatusId,
                );
                $this->db->insert('notifications', $input_data);
                // notifikasi pasif untuk provider
                $input_data = array(
                    'type' => "T",
                    'userId' => $providerId,
                    'transactionStatusId' => $transStatusId,
                );
                $this->db->insert('notifications', $input_data);
                if($this->db->affected_rows() > 0){
                    //$this->getNotification();
                    $this->get_notification();
                }
            }else{
                $data_output['success'] = "false";
                echo json_encode($data_output);
            }
        }else{
            $data_output['success'] = "false";
            echo json_encode($data_output);
        }
    }

    function finishTransaction(){
        //header('Content-Type: application/json');

        //cek session       
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(3) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

        $success = true;
        //$myId = $this->input->post('userId');
        //$idTransaction = $this->input->post('idTransaction');
        $myId = $id;
        $idTransaction = $str_id;
        $query = $this->db->query("SELECT n.transactionStatusId, t.userId FROM notifications n JOIN transactionStatus s ON s.id=n.transactionStatusId JOIN `transaction` t ON t.id=s.idTransaction WHERE s.idTransaction=".$idTransaction);
        $row = $query->row();
        // notifikasi sebelumnya di anggap sudah di baca
        foreach($query->result() as $row){
            if($row->userId != $myId){
                $success = false;
                break;
            }else{
                $this->db->where('transactionStatusId', $row->transactionStatusId);
                $this->db->delete('notifications');
            }
        }
        
        if($success){
            // menambahkan status menjadi Finish
            $now = date("Y-m-d H:i:s");
            $input_data = array(
                'idTransaction' => $idTransaction,
                'timeStamp' => $now,
                'status' => "F",
            );
            $this->db->insert('transactionStatus', $input_data);
        }
        if($success && $this->db->affected_rows() > 0 ){
            $query_status = $this->db->query("SELECT s.id, t.userId, t.providerId, t.idx, t.idTrip   FROM `transactionStatus` s JOIN transaction t ON s.idTransaction=t.id WHERE idTransaction=".$idTransaction." AND status='F' ORDER BY id DESC");
            $row_status = $query_status->row();
            $transStatusId = $row_status->id;
            $userid = $row_status->userId;
            $providerId = $row_status->providerId;
            $idx = $row_status->idx;
            $idTrip = $row_status->idTrip;
            if($transStatusId != NULL && $idx != NULL){
                if($this->overBookRealese($idx) == TRUE){
                    // notifikasi pasif untuk user
                    $input_data = array(
                        'type' => "T",
                        'userId' => $userid,
                        'transactionStatusId' => $transStatusId,
                    );
                    $this->db->insert('notifications', $input_data);
                    // notifikasi pasif untuk provider
                    $input_data = array(
                        'type' => "T",
                        'userId' => $providerId,
                        'transactionStatusId' => $transStatusId,
                    );
                    $this->db->insert('notifications', $input_data);
                    if($this->db->affected_rows() > 0){
                        $input_data = array(
                            'is_available' => 0,
                        );      
                        $this->db->where('id', $idTrip);
                        $this->db->update('trip', $input_data);
                        //$this->getNotification();
                        $this->get_notification();
                    }
                }else{
                    $data_output['success'] = "false";
                    echo json_encode($data_output);
                }
            }else{
                $data_output['success'] = "false";
                echo json_encode($data_output);
            }
        }else{
            $data_output['success'] = "false";
            echo json_encode($data_output);
        }
    }

    function getLog(){
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
            //cek isPremium
            if($this->session->userdata('isPremium')!=1){
                redirect('home','refresh');
            }
        }


        $userId = $id;
        if($userId != NULL){
            $query = $this->db->query("SELECT DISTINCT t.id, t.departTime AS `timestamp`, t.price, t.userId, t.providerId  FROM `transaction` t JOIN transactionStatus s ON s.idTransaction=t.id WHERE (userId = ".$userId." OR providerId = ".$userId.") AND s.`status`='F' AND t.paymentMethod = 'P'");
            $row = $query->row();
            if($query->num_rows() > 0){
                $count = 0;
                $data_output['success'] = "true";
                $saldo = $this->getSaldo($this->getRekening($userId));
                if($saldo>0){
                    $data_output['saldo'] = $saldo."";
                } else {
                    $data_output['saldo'] = "0";
                }
                foreach($query->result() as $row){
                    $data_output['log'][$count]['transaction_id'] = $row->id;       
                    $data_output['log'][$count]['timeStamp'] = date('d/m/Y',strtotime($row->timestamp)); 
                    $data_output['log'][$count]['priceInPoint'] = $row->price;  
                    $data_output['log'][$count]['userId'] = $row->userId;   
                    $data_output['log'][$count]['userName'] = $this->getNameById($row->userId); 
                    $data_output['log'][$count]['providerId'] = $row->providerId;   
                    $data_output['log'][$count]['providerName'] = $this->getNameById($row->providerId); 
                    $count++;   
                }
            }else{
                $data_output['success'] = "false";
            }
        }else{
            $data_output['success'] = "false";
        }
        // header('Content-Type: application/json');
        // echo json_encode($data_output);
        $data = array(
            //'output'=> $this->get($str_id,$id),
            'output' => $data_output,
            'page_title' => 'Log Transaksi',
            'page_content' => 'rekening',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id, 'isUpdate' => false);
        $this->load->view($this->_public_view, $data);
    }
    
    function getSaldo($rekening){
        
        $url = 'http://indobarter.com/api/index.php/api/ojegapi/ceknorekening/norekening/'.$rekening;
        
        $options = array(
            'http' => array(
                'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( $url, true, $context );
        $response = json_decode( $result , true);
        if(!empty($response['saldo'])){
            return $response['saldo'];
        }
        else            return false;
    
    }
    
    function getNotification(){
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }
        $userId = $id; echo $userId;
        $data_output['success'] = "true";
        $data_output['notifications'] = "";
        $query = $this->db->query("SELECT DISTINCT n.id AS notification_id, n.need_response, 
            s.`status`,s.timeStamp, t.* FROM notifications n JOIN transactionStatus s 
            ON n.transactionStatusId=s.id JOIN `transaction` t ON s.idTransaction=t.id 
            WHERE n.userId = ? AND n.status = 0", $this->session->userdata('user_id'));
        if($query->num_rows() > 0){
            $row_notif = $query->row(); 
            $count = 0;
            foreach($query->result() as $row_notif){
                if($row_notif->userId > 0 && $row_notif->providerId > 0){
                    $data_output['notifications']['transaction'][$count]['notification_id'] = $row_notif->notification_id;
                    $data_output['notifications']['transaction'][$count]['timeStamp'] = $row_notif->timeStamp;
                    $data_output['notifications']['transaction'][$count]['need_response'] = $row_notif->need_response;
                    $data_output['notifications']['transaction'][$count]['idTransaction'] = $row_notif->id;
                    $data_output['notifications']['transaction'][$count]['userId'] = $row_notif->userId;
                    $data_output['notifications']['transaction'][$count]['userName'] = $this->getNameById($row_notif->userId);
                    $data_output['notifications']['transaction'][$count]['userAvatar'] = $this->getAvatarById($row_notif->userId);
                    $data_output['notifications']['transaction'][$count]['userLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->userId);
                    $data_output['notifications']['transaction'][$count]['providerId'] = $row_notif->providerId;
                    $data_output['notifications']['transaction'][$count]['providerName'] = $this->getNameById($row_notif->providerId);
                    $data_output['notifications']['transaction'][$count]['providerAvatar'] = $this->getAvatarById($row_notif->providerId);
                    $data_output['notifications']['transaction'][$count]['providerLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->providerId);
                    if($row_notif->need_response == 1){
                        $data_output['notifications']['transaction'][$count]['departTime'] = $row_notif->departTime;
                        $data_output['notifications']['transaction'][$count]['source_label'] = $row_notif->source_label;
                        $data_output['notifications']['transaction'][$count]['source_latitude'] = $row_notif->source_latitude;
                        $data_output['notifications']['transaction'][$count]['source_longitude'] = $row_notif->source_longitude;
                        $data_output['notifications']['transaction'][$count]['destination_label'] = $row_notif->destination_label;
                        $data_output['notifications']['transaction'][$count]['destination_latitude'] = $row_notif->destination_latitude;
                        $data_output['notifications']['transaction'][$count]['destination_longitude'] = $row_notif->destination_longitude;
                    }
                    $data_output['notifications']['transaction'][$count]['price'] = $row_notif->price;
                    $data_output['notifications']['transaction'][$count]['paymentMethod'] = $row_notif->paymentMethod;
                    $data_output['notifications']['transaction'][$count]['status'] = $row_notif->status;
                    $count++;
                }
            }   
        }
        $query_premium = $this->db->query("SELECT * FROM notifications WHERE type LIKE 'P'  AND status = 0 AND userId =  ".$this->session->userdata('user_id'));
        if($query_premium->num_rows() > 0){
            $row_premium = $query_premium->row(); 
            $data_output['notifications']['premium'][0]['notification_id'] = $row_premium->id;
            $data_output['notifications']['premium'][0]['need_response'] = $row_premium->need_response;
            $data_output['notifications']['premium'][0]['userId'] = $row_premium->userId;
            $data_output['notifications']['premium'][0]['userName'] = $this->getNameById($row_premium->userId);
        }
        header('Content-Type: application/json');
        echo json_encode($data_output);
    }

    function get($str_id='',$id=''){

        $data_output['success'] = "false";
        $userid = $str_id;
        $myid = $id;
        $myStatus = $this->input->post('myStatus');
        $query_user = $this->db->query("SELECT username, name,password,isPremium,entryDate,lastUpdated,avatar,lastUpdatedAvatar,gender, (SELECT SUM(rateValue)/COUNT(rateValue) FROM rating WHERE providerId = ".$userid." AND rateValue >0) AS rate, (SELECT COUNT(rateValue) FROM rating WHERE providerId = ".$userid." AND rateValue >0) AS voterCount FROM `user` WHERE `id` = '".$userid."'");
        $row_user = $query_user->row();
        if($query_user->num_rows() > 0){
            $data_output['success'] = "true";
            $data_output['id'] = $userid;
            $data_output['username'] = $row_user->username;
            $data_output['password'] = $row_user->password;
            $data_output['name'] = $row_user->name;
            $data_output['isPremium'] = $row_user->isPremium;
            $data_output['entryDate'] = $row_user->entryDate;
            $data_output['lastUpdated'] = $row_user->lastUpdated;
            $data_output['avatar'] = $row_user->avatar;
            $data_output['lastUpdatedAvatar'] = $row_user->lastUpdatedAvatar;
            $data_output['gender'] = $row_user->gender;
            $data_output['rate'] = "".$row_user->rate;
            $data_output['voterCount'] = "".$row_user->voterCount;

            $query_userprofile = $this->db->query("SELECT phoneNumber,bio,address,avatarMotor,lastUpdatedAvatarMotor,motorDesc,motorYear,licenseNumber,deliverCounter,email FROM `userprofile` WHERE `idUser` = '".$userid."'");
            $row_userprofile = $query_userprofile->row();
            $data_output['phoneNumber'] = $row_userprofile->phoneNumber;
            $data_output['bio'] = $row_userprofile->bio;
            $data_output['address'] = $row_userprofile->address;
            $data_output['avatarMotor'] = $row_userprofile->avatarMotor;
            $data_output['lastUpdatedAvatarMotor'] = $row_userprofile->lastUpdatedAvatarMotor;
            $data_output['licenseNumber'] = $row_userprofile->licenseNumber;
            $data_output['motorDesc'] = $row_userprofile->motorDesc;
            $data_output['motorYear'] = $row_userprofile->motorYear;
            $data_output['deliverCounter'] = $row_userprofile->deliverCounter;
            $data_output['email'] = $row_userprofile->email;
        }
        
        $query = $this->db->query("SELECT t.* FROM trip t JOIN `user` u ON u.id=t.userId WHERE departTime >= '".date("Y-m-d H:i:s")."' AND userId = ".$userid." AND t.is_available=1 ORDER BY departTime LIMIT 1");
        if($query->num_rows() < 1){
            $data_output['currentTrip'] = "";
        }else{
            $row = $query->row(); 
            $data_output["currentTrip"][0]["id"] = $row->id;
            $data_output["currentTrip"][0]["status"] = $row->status;
            $data_output["currentTrip"][0]["source_label"] = $row->source_label;
            $data_output["currentTrip"][0]["source_latitude"] = $row->source_latitude;
            $data_output["currentTrip"][0]["source_longitude"] = $row->source_longitude;
            $data_output["currentTrip"][0]["destination_label"] = $row->destination_label;
            $data_output["currentTrip"][0]["destination_latitude"] = $row->destination_latitude;
            $data_output["currentTrip"][0]["destination_longitude"] = $row->destination_longitude;
            $data_output["currentTrip"][0]["via"] = $row->via;
            $data_output["currentTrip"][0]["priceInRupiah"] = $row->priceInRupiah;
            $data_output["currentTrip"][0]["priceInPoint"] = $row->priceInPoint;
            $data_output["currentTrip"][0]["departTime"] = $row->departTime;
            $data_output["currentTrip"][0]["notes"] = $row->notes;
            if($row->status == 'P' && $myid != $userid)             $data_output["pickUpStatus"] = $this->getPickupStatus($myid,$userid);
        }
        
        
        $privacy_criteria = " AND t.privacy = 0";
        if($myid === $userid)           $privacy_criteria = "";

        $query = $this->db->query("SELECT COUNT(*) AS historyCount FROM `transaction` t JOIN transactionStatus s ON t.id=s.idTransaction WHERE s.`status` = 'F' AND (userId = ".$userid." OR providerId = ".$userid.")".$privacy_criteria.' ORDER BY t.id DESC LIMIT 3');
        $row = $query->row();
        $historyCount = $row->historyCount;
        $data_output["viewMoreHistory"] = "false";
        $data_output['history'] = "";
        if($historyCount > 0){
            if($historyCount > 3){
                $data_output["viewMoreHistory"] = "true";
            }
            $query = $this->db->query("SELECT DISTINCT t.* FROM `transaction` t JOIN transactionStatus s ON t.id=s.idTransaction WHERE s.`status` = 'F' AND (userId = ".$userid." OR providerId = ".$userid.")".$privacy_criteria.' ORDER BY t.id DESC LIMIT 3');
            $row = $query->row();
            if($query->num_rows() < 1 || $historyCount < 1){
                $data_output['history'] = "";
            }else{
                $count = 0;
                foreach($query->result() as $row){
                    $data_output["history"][$count]["id"] = $row->id;
                    $data_output["history"][$count]["departTime"] = $row->departTime;
                    $data_output["history"][$count]["userId"] = $row->userId;
                    $data_output["history"][$count]["name"] = $this->getNameById($row->userId);
                    $data_output["history"][$count]["avatar"] = $this->getAvatarById($row->userId);
                    $data_output["history"][$count]["lastUpdatedAvatar"] = $this->getLastUpdatedAvatar($row->userId);
                    $data_output["history"][$count]["providerId"] = $row->providerId;
                    $data_output["history"][$count]["providerName"] = $this->getNameById($row->providerId);
                    $data_output["history"][$count]["providerAvatar"] = $this->getAvatarById($row->providerId);
                    $data_output["history"][$count]["providerLastUpdatedAvatar"] = $this->getLastUpdatedAvatar($row->providerId);
                    $data_output["history"][$count]["source_label"] = $row->source_label;
                    $data_output["history"][$count]["source_latitude"] = $row->source_latitude;
                    $data_output["history"][$count]["source_longitude"] = $row->source_longitude;
                    $data_output["history"][$count]["destination_label"] = $row->destination_label;
                    $data_output["history"][$count]["destination_latitude"] = $row->destination_latitude;
                    $data_output["history"][$count]["destination_longitude"] = $row->destination_longitude;
                    $data_output["history"][$count]["paymentMethod"] = $row->paymentMethod;
                    $data_output["history"][$count]["price"] = $row->price;
                    $idTrip = $row->idTrip;
                    $query = $this->db->query("select via,priceInRupiah,priceInPoint from trip where id =".$idTrip);
                    $row = $query->row();
                    $data_output["history"][$count]["via"] = $row->via;
                    $count++;
                }
                if($count == 0)             $data_output['history'] = "";
            }
        }
        
        $providerid = $this->input->post('providerId');
        
        $query = $this->db->query("SELECT COUNT(*) AS voterCount FROM rating WHERE providerId = ".$userid);
        $row = $query->row();
        $voterCount = $row->voterCount;
        $data_output['viewMoreComments'] = "false";
        $data_output['comments'] = "";
        if($voterCount > 0){
            if($voterCount > 3){
                $data_output['viewMoreComments'] = "true";
            }
            $count = 0;
            $query = $this->db->query("SELECT reviewerId, u.`name`, u.avatar, u.lastUpdatedAvatar, rateValue, `comment` FROM rating r JOIN `user` u ON u.id=r.reviewerId WHERE providerId = ".$userid." AND rateValue > 0 AND `comment` IS NOT NULL AND `comment` <> '' LIMIT 3");
            $row = $query->row();
            if($query->num_rows() < 1 || $voterCount < 1){
                $data_output['comments'] = "";
            }else{
                foreach($query->result() as $row){
                    $data_output['comments'][$count]['reviewerId'] = $row->reviewerId;
                    $data_output['comments'][$count]['name'] = $row->name;
                    $data_output['comments'][$count]['avatar'] = $row->avatar;
                    $data_output['comments'][$count]['lastUpdatedAvatar'] = $row->lastUpdatedAvatar;
                    /*$data_output['rating'][$count]['rateValue'] = ''.$row->rateValue;*/
                    $data_output['comments'][$count]['comment'] = $row->comment;
                    $count++;
                }
                if($count == 0)             $data_output['comments'] = "";
            }
        }
        
        $query = $this->db->query("SELECT `comment`, rateValue FROM rating  WHERE providerId = ".$userid." AND reviewerId = ".$myid." LIMIT 1");
        $row = $query->row();
        if($query->num_rows() < 1){
            $data_output['myRating'] = "";
        }else{
            $data_output['myRating'][0]['rateValue'] = ''.$row->rateValue;
            $data_output['myRating'][0]['comment'] = $row->comment;
        }
        return $data_output;
     }

     function getPickupStatus($myid,$userid){
        $query = $this->db->query("SELECT ts.`status` FROM transactionStatus ts JOIN `transaction` t ON t.id=ts.idTransaction WHERE t.userId=".$myid." AND t.providerId=".$userid." ORDER BY ts.`timeStamp` DESC LIMIT 1");
        if($query->num_rows()>0){
            $row = $query->row();
            if($row->status == "F" || $row->status == "C")          return 'A';
            else            return $row->status;
        }else{
            return 'A';
        }
    }

    function get_notification(){
        //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }
        $data_output['success'] = "true";
        $data_output['notifications'] = "";
        $query = $this->db->query("SELECT DISTINCT n.id AS notification_id, n.need_response, s.`status`,s.timeStamp, t.* FROM notifications n JOIN transactionStatus s ON n.transactionStatusId=s.id JOIN `transaction` t ON s.idTransaction=t.id WHERE n.status = 0 AND n.userId = ".$id." order by s.timeStamp desc");
        if($query->num_rows() > 0){
            $row_notif = $query->row(); 
            $count = 0;
            foreach($query->result() as $row_notif){
                if($row_notif->userId > 0 && $row_notif->providerId > 0){
                    $data_output['notifications']['transaction'][$count]['notification_id'] = $row_notif->notification_id;
                    $data_output['notifications']['transaction'][$count]['timeStamp'] = $row_notif->timeStamp;
                    $data_output['notifications']['transaction'][$count]['need_response'] = $row_notif->need_response;
                    $data_output['notifications']['transaction'][$count]['idTransaction'] = $row_notif->id;
                    $data_output['notifications']['transaction'][$count]['userId'] = $row_notif->userId;
                    $data_output['notifications']['transaction'][$count]['userName'] = $this->getNameById($row_notif->userId);
                    $data_output['notifications']['transaction'][$count]['userAvatar'] = $this->getAvatarById($row_notif->userId);
                    $data_output['notifications']['transaction'][$count]['userLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->userId);
                    $data_output['notifications']['transaction'][$count]['providerId'] = $row_notif->providerId;
                    $data_output['notifications']['transaction'][$count]['providerName'] = $this->getNameById($row_notif->providerId);
                    $data_output['notifications']['transaction'][$count]['providerAvatar'] = $this->getAvatarById($row_notif->providerId);
                    $data_output['notifications']['transaction'][$count]['providerLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->providerId);
                    //if($row_notif->need_response == 1){
                        $data_output['notifications']['transaction'][$count]['departTime'] = $row_notif->departTime;
                        $data_output['notifications']['transaction'][$count]['source_label'] = $row_notif->source_label;
                        $data_output['notifications']['transaction'][$count]['source_latitude'] = $row_notif->source_latitude;
                        $data_output['notifications']['transaction'][$count]['source_longitude'] = $row_notif->source_longitude;
                        $data_output['notifications']['transaction'][$count]['destination_label'] = $row_notif->destination_label;
                        $data_output['notifications']['transaction'][$count]['destination_latitude'] = $row_notif->destination_latitude;
                        $data_output['notifications']['transaction'][$count]['destination_longitude'] = $row_notif->destination_longitude;
                    //}
                    $data_output['notifications']['transaction'][$count]['price'] = $row_notif->price;
                    $data_output['notifications']['transaction'][$count]['paymentMethod'] = $row_notif->paymentMethod;
                    $data_output['notifications']['transaction'][$count]['status'] = $row_notif->status;
                    $count++;
                }
            }   
        }
        $query_premium = $this->db->query("SELECT * FROM notifications WHERE type LIKE 'P' AND status = 0 AND userId =  ".$id);
        if($query_premium->num_rows() > 0){
            $row_premium = $query_premium->row(); 
            $data_output['notifications']['premium'][0]['notification_id'] = $row_premium->id;
            $data_output['notifications']['premium'][0]['need_response'] = $row_premium->need_response;
            $data_output['notifications']['premium'][0]['userId'] = $row_premium->userId;
            $data_output['notifications']['premium'][0]['userName'] = $this->getNameById($row_premium->userId);
        }
        //header('Content-Type: application/json');
        //echo json_encode($data_output);
        $data = array(
                'output' => $data_output,
                'page_title' => 'Notifikasi',
                'page_content' => 'notifikasi',
                'isLogin' => $isLogin, 'user'=>$user, 'id' => $id
                    );
        $this->load->view($this->_public_view, $data);
    }

}

?>
